package com.icoolkj.ms.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.icoolkj.ms.api.auth.model.AuthAccount;
import com.icoolkj.ms.api.auth.vo.AuthAccountVO;
import com.icoolkj.ms.common.security.bo.AuthAccountInVerifyBO;
import com.icoolkj.ms.api.auth.bo.UserInfoInTokenBO;
import com.icoolkj.ms.common.core.enums.AccountStatusEnum;
import com.icoolkj.ms.auth.mapper.AuthAccountMapper;
import com.icoolkj.ms.auth.service.IAuthAccountService;
import com.icoolkj.ms.common.core.response.ServerResponseEntity;
import com.icoolkj.ms.common.core.utils.BeanUtil;
import com.icoolkj.ms.common.core.utils.PrincipalUtil;
import com.icoolkj.ms.common.security.enums.InputUserNameEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author icoolkj
 * @version 1.0
 * @description 认证用户服务实现
 * @createDate 2025/02/04 16:33
 */
@Service
public class AuthAccountServiceImpl implements IAuthAccountService {

    private static final Logger logger = LoggerFactory.getLogger(AuthAccountServiceImpl.class);

    @Autowired
    private AuthAccountMapper sysAccountMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ServerResponseEntity<UserInfoInTokenBO> getUserInfoInTokenByInputUserNameAndPassword(String inputUserName, String password, String userType) {

        if (StrUtil.isBlank(inputUserName)) {
            return ServerResponseEntity.fail("用户名不能为空");
        }

        if (StrUtil.isBlank(password)) {
            return ServerResponseEntity.fail("密码不能为空");
        }

        InputUserNameEnum inputUserNameEnum = null;

        // 用户名
        if (PrincipalUtil.isUserName(inputUserName)) {
            inputUserNameEnum = InputUserNameEnum.USERNAME;
        }

        // 手机号
        if (PrincipalUtil.isMobile(inputUserName)) {
            inputUserNameEnum = InputUserNameEnum.PHONE;
        }

        // 邮箱
        if (PrincipalUtil.isEmail(inputUserName)) {
            inputUserNameEnum = InputUserNameEnum.EMAIL;
        }

        if (inputUserNameEnum == null) {
            logger.error("登录用户：{} 用户名不正确", inputUserName);
            return ServerResponseEntity.fail("请输入正确的用户名");
        }

        AuthAccountInVerifyBO authUserInVerify = getAuthAccountInVerifyByInputUserName(inputUserNameEnum.value(), inputUserName, userType);
        if (authUserInVerify == null) {
            return ServerResponseEntity.fail("用户名或密码不正确");
        }

        if (ObjectUtil.equals(authUserInVerify.getStatus(), AccountStatusEnum.DISABLE.getCode())) {
            logger.error("登录用户：{} 已被禁用", inputUserName);
            return ServerResponseEntity.fail("用户已禁用，请联系客服");
        }

        if(!passwordEncoder.matches(password, authUserInVerify.getPassword())) {
            return ServerResponseEntity.fail("用户名或密码不正确");
        }

        return ServerResponseEntity.success(BeanUtil.map(authUserInVerify, UserInfoInTokenBO.class));
    }

    @Override
    public ServerResponseEntity<UserInfoInTokenBO> getUserInfoInTokenByPhone(String phoneNumber, String userType) {
        if (StrUtil.isBlank(phoneNumber)) {
            return ServerResponseEntity.fail("手机号不能为空");
        }

        if (!PrincipalUtil.isMobile(phoneNumber)) {
            logger.error("登录手机号：{} 格式不正确", phoneNumber);
            return ServerResponseEntity.fail("请输入正确的手机号");
        }

        AuthAccountInVerifyBO authUserInVerify = getAuthAccountInVerifyByInputUserName(InputUserNameEnum.PHONE.value(), phoneNumber, userType);
        if (authUserInVerify == null) {
            return ServerResponseEntity.fail("该手机号未注册");
        }

        if (ObjectUtil.equals(authUserInVerify.getStatus(), AccountStatusEnum.DISABLE.getCode())) {
            logger.error("登录手机号：{} 已被禁用", phoneNumber);
            return ServerResponseEntity.fail("用户已禁用，请联系客服");
        }

        return ServerResponseEntity.success(BeanUtil.map(authUserInVerify, UserInfoInTokenBO.class));
    }

    @Override
    public ServerResponseEntity<UserInfoInTokenBO> getUserInfoInTokenByEmail(String email, String userType) {
        if (StrUtil.isBlank(email)) {
            return ServerResponseEntity.fail("邮箱不能为空");
        }

        if (!PrincipalUtil.isEmail(email)) {
            logger.error("登录邮箱：{} 格式不正确", email);
            return ServerResponseEntity.fail("请输入正确的邮箱");
        }

        AuthAccountInVerifyBO authUserInVerify = getAuthAccountInVerifyByInputUserName(InputUserNameEnum.EMAIL.value(), email, userType);
        if (authUserInVerify == null) {
            return ServerResponseEntity.fail("该邮箱未注册");
        }

        if (ObjectUtil.equals(authUserInVerify.getStatus(), AccountStatusEnum.DISABLE.getCode())) {
            logger.error("登录邮箱：{} 已被禁用", email);
            return ServerResponseEntity.fail("用户已禁用，请联系客服");
        }

        return ServerResponseEntity.success(BeanUtil.map(authUserInVerify, UserInfoInTokenBO.class));
    }

    private AuthAccountInVerifyBO getAuthAccountInVerifyByInputUserName(Integer inputUserNameType, String inputUserName, String userType){
        return sysAccountMapper.getAuthAccountInVerifyByInputUserName(inputUserNameType, inputUserName, userType);
    }

    @Override
    public ServerResponseEntity<AuthAccountVO> getByInputUsernameAndUserType(Integer inputUserNameType, String inputUserName, String userType){
        AuthAccountVO sysAccountVO = sysAccountMapper.getByInputUsernameAndUserType(inputUserNameType, inputUserName, userType);
        return ServerResponseEntity.success(sysAccountVO);
    }

    @Override
    public int saveAuthAccount(AuthAccount authAccount){
        return sysAccountMapper.saveAuthAccount(authAccount);
    }

    @Override
    public int deleteByUid(Long uid) {
        if (uid == null) {
            logger.error("删除用户时，用户ID不能为空");
            return 0;
        }
        logger.info("逻辑删除用户，用户ID：{}", uid);
        return sysAccountMapper.deleteByUid(uid);
    }

    @Override
    public int batchDeleteByUids(Long[] uids) {
        if (uids == null || uids.length == 0) {
            logger.error("批量删除用户时，用户ID数组不能为空");
            return 0;
        }
        logger.info("批量逻辑删除用户，用户ID数组长度：{}", uids.length);
        return sysAccountMapper.batchDeleteByUids(uids);
    }
}
